/*	
*	INA219 Driver for STC89C52
*	Author: Kituro
*	Created: Someday in 2021.3
*	Last changed: 2021.7.10
*	Program Size : Unknown
*/

#include <reg52.h>
#include <intrins.h>
#include "IIC_Protocol_for8051.h"
#include "SegmentDisplayLite.h"
#define INA219_WR_Operation 0x80
#define INA219_RD_Operation 0x81
#define ACK 0
#define NACK 1	
#define SHUNT_RES 0.1 //Shunt Resistor 0.1 ohm
sbit led = P1^0;



unsigned int INA219_ReadReg(unsigned char RegBase)
{
        unsigned short RegValue = 0;
		
        IIC_Start();
        IIC_SendOneByte(INA219_WR_Operation);
        if(!IIC_RecvACK_Error())
        {
                IIC_SendOneByte(RegBase);
                if(!IIC_RecvACK_Error())
                {		
						led = 0;
                        //IIC_Stop();
                        IIC_Start();
                        IIC_SendOneByte(INA219_RD_Operation);
                        if(!IIC_RecvACK_Error())
                        {
                                RegValue = IIC_RecvOneByte();
                                IIC_SendACK(ACK);
                                RegValue = RegValue << 8;
                                RegValue |= IIC_RecvOneByte();
                                IIC_SendACK(NACK);
                        }
                }
        }
        IIC_Stop();

        return RegValue;
}

bit INA219_WriteReg(unsigned char RegBase, unsigned int RegValue)
{
        bit WrRegError = 1;

        IIC_Start();
        IIC_SendOneByte(INA219_WR_Operation);
        if(!IIC_RecvACK_Error())
        {
                IIC_SendOneByte(RegBase);
                if(!IIC_RecvACK_Error())
                {
                        IIC_SendOneByte((RegValue & 0xFF00) >> 8);
                        IIC_RecvACK_Error();
                        IIC_SendOneByte(RegValue & 0x00FF);
                        WrRegError = IIC_RecvACK_Error();
                }
        }
        IIC_Stop();

        return !WrRegError;
}

void INA219_Init(){
	INA219_WriteReg(0x00, 0x399F);	//Configuration Register Set: Non-reset, Bus Voltage 32V FSR, PGA Gain 320mv, both ADC 12-bit Samples, Shunt and Bus, Continous
	INA219_WriteReg(0x05, 0x1000);	//Calibration Register Set: Cal = 1000h, Current_LSB 0.0001A, R_Shunt = 0.1 ohm
}
unsigned int INA219_GetCurrent(void)
{
        unsigned int CurrentRegVal;
        CurrentRegVal = INA219_ReadReg(0x04);
        return CurrentRegVal;//>> 3;                                                                //0.125mA/bit
}